<template>
  <!--患者列表 -->
  <a-space direction="vertical" class="w-[300px]">
    <a-input-group compact>
      <a-select
        v-model:value="searchState.lisInstrumentId"
        class="w-full"
        :field-names="{ label: 'instrumentName', value: 'id' }"
        placeholder="请选择"
        :options="instrumentList"
        @change="onInstrumentChange"
      />
    </a-input-group>
    <a-range-picker v-model:value="searchState.rangeDate" class="w-full" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="selectDate" />
    <div class="flex items-center justify-between">
      <a-input-search v-model:value="searchState.pyjm" placeholder="姓名/助记码/卡号/身份证号/收据号" @search="getSideData" />
      <a-button class="ml-1" type="primary" :disabled="!store.currentPatient.lsh" @click="medicalOpen = true">医保</a-button>
    </div>
    <a-radio-group v-model:value="searchState.status" button-style="solid" class="flex radio-style" @change="getSideData">
      <a-radio-button value="">全部({{ listCount.all }})</a-radio-button>
      <a-radio-button :value="1">已审核({{ listCount.ysh }})</a-radio-button>
      <a-radio-button :value="0">未审核({{ listCount.wsh }})</a-radio-button>
    </a-radio-group>
  </a-space>
  <div class="flex-1 overflow-auto">
    <a-checkbox-group v-model:value="checkedList">
      <BaseList :data-source="store.sideList" :loading="loading" class="w-[300px]">
        <template #renderItem="{ item }">
          <div class="py-2 px-3 relative overflow-hidden" :class="{ 'active-item': store.currentPatient.lsh === item.lsh }" @click="onSelect(item)">
            <img v-if="item.status === '1'" :src="statusIcon" alt="" class="absolute -left-1 -top-1 z-0 w-12" />
            <div class="flex justify-between">
              <div class="text-base font-bold text-primary truncate w-16" :title="item.brName">{{ item.brName }}</div>
              <div class="flex w-16 ml-1 truncate justify-between items-center">
                <div class="text-sm">{{ item.brXb }}</div>
                <div class="text-sm">{{ item.brAge }}</div>
                <div>
                  <a-button v-if="item.applyPath === 0" type="primary" shape="circle" size="small" class="ml-1">门</a-button>
                  <a-button v-if="item.applyPath === 1" type="primary" shape="circle" size="small" class="bg-lime-500 ml-1">住</a-button>
                  <a-button v-if="item.applyPath === 2" type="primary" shape="circle" size="small" class="bg-orange-400 ml-1">体</a-button>
                </div>
              </div>
              <div class="text-base font-bold text-primary truncate flex-1 text-right">{{ item.recordLsh }}</div>
              <img v-if="item.isReportPrinted" :src="fileReadIcon" alt="已打印" class="w-[83px] h-[83px] absolute -top-2 right-12" />
            </div>
            <div class="flex justify-between pt-2 z-10">
              <div class="flex-1 text-grey truncate">
                <RoundTag v-if="item.crisisStatus === '1'" bg-color="#f00" class="mr-1">危</RoundTag>
                <a-tooltip v-if="item.items.length > 15" :title="item.items" placement="topLeft" :mouse-enter-delay="0.6">
                  {{ item.items }}
                </a-tooltip>
                <span v-else>{{ item.items }}</span>
              </div>
              <div class="w-16 text-right text-grey">{{ item.applyDoctorName }}</div>
            </div>
            <!-- 选择框 -->
            <div
              v-if="isCheck"
              class="absolute right-0 top-0 w-2/3 z-20 text-right bg-gradient-to-l from-[#00000050] flex items-center justify-end pr-2 h-full"
            >
              <a-checkbox :value="item.lsh" />
            </div>
          </div>
        </template>
      </BaseList>
    </a-checkbox-group>
  </div>
  <!-- 医保登记 -->
  <MedicalRegistration v-model:open="medicalOpen" :patient-info="{ ...store.currentPatient }" @success="store.getOrderData()" />
  <a-space class="flex w-full pt-2">
    <a-button type="primary" ghost class="w-24" @click="onChecking()">{{ isCheck ? '取消选择' : '选择' }}</a-button>
    <a-button type="primary" :disabled="isBtnDisabled" @click="onBatchCheck()">批量审核</a-button>
    <a-button type="primary" :disabled="checkedList.length === 0" @click="onPrints">批量打印</a-button>
  </a-space>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import statusIcon from '@/assets/icons/checked.png'
import fileReadIcon from '@/assets/images/file-read-icon2.png'
import { post } from '@/utils/request'
import MedicalRegistration from '@/views/out-registration/statistics/register-query/components/MedicalRegistration.vue'
import useStore from '../store'

const emit = defineEmits(['change'])
const store = useStore()
const loading = ref(true)
const searchState = ref({
  pyjm: '',
  lisInstrumentId: '',
  status: '',
  rangeDate: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})

const onSelect = (item) => {
  // if (store.currentPatient?.recordCode === item.recordCode) {
  //   store.reset()
  // } else {

  // }
  store.currentPatient.lsh = item.lsh
  store.barCode = ''
  store.getOrderData(2)
}
const checkedList = ref([])
const isCheck = ref(false)
const medicalOpen = ref(false)
const isBtnDisabled = ref(true)
const onChecking = () => {
  isCheck.value = !isCheck.value
  checkedList.value = []
}
//批量审核
const onBatchCheck = async () => {
  const { code, msg } = await post('/lis/LisRecord/doAuditLisRecord', { lisApplyLshList: checkedList.value })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success(msg || '操作成功')
  getSideData()
}
const selectDate = async () => {
  getSideData()
}
// 获取申请单各状态数量
const listCount = ref({ all: 0, wsh: 0, ysh: 0 })
const queryListCount = async () => {
  const {
    code,
    data = {},
    msg
  } = await post('/lis/LisApply/getLisApplyNumber', {
    ...searchState.value,
    stdate: searchState.value.rangeDate[0],
    eddate: searchState.value.rangeDate[1]
  })
  if (code !== 0) return message.error(msg || '查询失败')
  listCount.value = data
}
// 获取仪器列表
const instrumentList = ref([])
const getInstrumentList = async () => {
  const { code, data = [], msg } = await post('/lis/InstrumentType/getInstrumentList', { status: 1 })
  if (code !== 0) return message.error(msg || '查询失败')
  instrumentList.value = data
  //选择第一项
  data[0]?.id && onInstrumentChange(data[0].id, data[0])
}
// 获取侧边栏列表
const getSideData = async () => {
  store.isLoading = true
  loading.value = true
  const { code, data, msg } = await post('/lis/LisApply/getLisReportList', {
    ...searchState.value,
    notStatus: 2,
    stdate: searchState.value.rangeDate[0],
    eddate: searchState.value.rangeDate[1]
  })
  if (code !== 0) return message.error(msg || '请求失败')
  loading.value = false
  store.isLoading = false
  queryListCount()
  store.sideList = data || []
  store.recordDate = dayjs().format('YYYY-MM-DD')
  emit('change', { stdate: searchState.value.rangeDate[0], eddate: searchState.value.rangeDate[1], ...searchState.value })
  if (data.length) {
    // store.currentPatient = data[0]  // 默认选中左侧第一个
    store.getOrderData()
  } else {
    store.currentPatient = {}
  }
}

// 批量打印
const onPrints = () => {
  checkedList.value.forEach(async (item) => {
    const { code, msg, data } = await post('/lis/lisPrint/printLisRecord', { lsh: item, dylx: 2 })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  })
}

//切换仪器
const onInstrumentChange = (val, option) => {
  searchState.value.lisInstrumentId = val
  searchState.value.instrumentTypeId = option.instrumentTypeId
  store.currentInstrument = option
  getSideData()
  store.getSampleNumber() //获取样本号
}
watch(
  () => checkedList.value,
  (val) => {
    if (val.length > 0) {
      isBtnDisabled.value = false
      checkedList.value
        .filter((item) => {
          return store.sideList.filter((items) => items.lsh === item)[0].status === '1'
        })
        .map(() => (isBtnDisabled.value = true))
    } else {
      isBtnDisabled.value = true
    }
  }
)
defineExpose({
  getSideData,
  onSelect
})
onMounted(() => {
  getInstrumentList()
})
</script>
<style lang="less" scoped>
.radio-style {
  :deep(.ant-radio-button-wrapper) {
    width: 33.4%;
    padding: 0;
    text-align: center;
  }
}
.active-item {
  background-color: var(--secondary-color) !important;
  border: 1px solid var(--primary-color) !important;
  border-radius: 4px !important;
  &:hover {
    background-color: var(--secondary-color) !important;
  }
}
</style>
